package com.changgou.filter;

import com.changgou.util.JwtUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class AuthFilter implements GlobalFilter, Ordered {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        //1.获取请求
        ServerHttpRequest request = exchange.getRequest();
        //2.获取响应
        ServerHttpResponse response = exchange.getResponse();
        //3.获取请求URL
        String url = request.getURI().getPath();
        //4.根据URL判断是否是登录操作，如果是则放行
        if(url.contains("/admin/login")){
            logger.info("登录URL放行.....");
            return chain.filter(exchange);
        }

        //5.如果不是登录操作，继续获取请求头的token
        String token = request.getHeaders().getFirst("token");

        //6.判断token是否有值，如果没有值则拒绝，有如果有值继续
        if(StringUtils.isEmpty(token)){
            logger.info("当前请求没有TOKEN，请求URL：{}",url );
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //7.解析TOKEN，如果解析失败则拒绝
        try {
            JwtUtil.parseJWT(token);
        } catch (Exception e) { //解析失败的原因：头、载荷、签名造假，或者JWT已经过期
            e.printStackTrace();
            logger.error("当前请求的TOKEN不合法，请求URL：{}",url );
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //8.解析成功放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
